part of '../photo_main_page.dart';

class ImageItem extends StatelessWidget {
  final AssetEntity? entity;

  final Color? themeColor;
  final SelectedProvider selectedProvider;

  final int? size;

  final LoadingDelegate? loadingDelegate;

  final BadgeDelegate? badgeDelegate;


  const ImageItem({
    Key? key,
    this.entity,
    this.themeColor,
    required this.selectedProvider,
    this.size = 64,
    this.loadingDelegate,
    this.badgeDelegate,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var thumb = ImageLruCache.getData(entity, size);
    if (thumb != null) {
      return _buildImageItem(context, thumb);
    }

    return FutureBuilder<Uint8List?>(
      future: entity!.thumbDataWithSize(size!, size!),
      builder: (BuildContext context, AsyncSnapshot<Uint8List?> snapshot) {
        var futureData = snapshot.data;
        if (snapshot.connectionState == ConnectionState.done &&
            futureData != null) {
          ImageLruCache.setData(entity, size, futureData);
          return _buildImageItem(context, futureData);
        }
        return Center(
          child: () sync* {
            yield loadingDelegate!.buildPreviewLoading(
              context,
              entity,
              themeColor,
            );
          }().last,
        );
      },
    );
  }

  Widget _buildImageItem(BuildContext context, Uint8List data) {
    final itemEntity = entity!;
    var image = Image.memory(
      data,
      width: double.infinity,
      height: double.infinity,
      fit: BoxFit.cover,
    );
    var badge;
    final badgeBuilder =
    badgeDelegate?.buildBadge(
        context, itemEntity.type, itemEntity.videoDuration);
    if (badgeBuilder == null) {
      badge = Container();
    } else {
      badge = badgeBuilder;
    }
    Options? options = PhotoPickerProvider.of(context)!.options;
    return Stack(
      children: <Widget>[
        image,
        Positioned.fill(
            child: IgnorePointer(
              child: Container(
                color: () sync* {
                  bool maxSelected =false;
                  Color maskColor=Colors.transparent;
                  if(options!=null){
                    maxSelected=(selectedProvider.selectedCount) == options.maxSelected;
                    maskColor=options.maxMaskColor??Colors.transparent;
                  }
                  bool currentIsSelected=false;
                  if(maxSelected){
                    currentIsSelected=selectedProvider.containsEntity(itemEntity);
                  }
                  if (maxSelected&&!currentIsSelected) {
                    yield maskColor;
                  } else {
                    yield Colors.transparent;
                  }
                }().last,
              ),
            )),
        IgnorePointer(
          child: badge,
        ),
      ],
    );
  }
}
